﻿using System.Diagnostics;

namespace BlogsAPI.Shorteners
{
    using System.Web;
    using System;
    using System.IO;
    using System.Net;
    using Abstract;

    /// <summary>
    /// Cligs tracks the traffic going through your links. Not just that, Cligs has unique tracking and redirection features that give you the best insight:
    ///Cligs is free! You do not pay us anything to use all of its awesome features.
    ///Private analytics No one apart from you can see your stats data. This way your competitors will not be able to see your marketing campaigns and how successful they are. To do that, you will need to register and sign into Cligs.
    ///Real time analytics You want to know what is working now so you can adjust quickly.
    ///Deepest analytics around Lots of interactive charts and data, like a world map, that show you where your traffic is coming from and who are the people clicking on your links. 
    ///Social media monitoring Cligs keeps track in real time of who tweets your link, who shares it on Friendfeed, who links to it, who blogs about it, who writes a blog comment about it, and more. Not just that, Cligs does that for the destination URL too! All in one handy interface.
    ///Multiple links to the same destination Share different links on different services like Twitter, Facebook, and email and track the traffic and watch it spread across services.
    ///Search engine optimized Cligs uses the 301 forward which is recommended by Google, Yahoo!, and Microsoft to help you get the best rankings benefits.
    ///Easy to tweet With one click you can send your short URLs to Twitter. No fuss.
    ///Custom URLs Get your brand name in your links! You can create links like http://cli.gs/MyBrand.
    ///Real time analytics You want to know what is working now so you can adjust quickly.
    /// </summary>
    /// <seealso cref="http://blog.cli.gs/api"/>
    /// <remarks>
    /// There are only 2 functions:
    /// 1) http://cli.gs/api/v1/cligs/create?url=1&title=2&key=3&appid=4
    /// 2) http://cli.gs/api/v1/cligs/expand?clig=1
    /// </remarks>
    [SingleShortener(Link = "http://cli.gs")]
    public class Cligs : Shortener
    {
        /// <summary>
        /// Конструктор по умолчанию
        /// </summary>
        public Cligs()
        {
        }

        /// <summary>
        /// Заполняем данными пользователя
        /// Работа с имеющимся Tr.im аккаунтом
        /// </summary>
        /// <param name="apikey">ключ приложения</param>
        public Cligs(String apikey)
        {
            _apikey = apikey;
        }

        /// <summary>
        /// Преобразование одного типа данных в другой
        /// </summary>
        /// <param name="sInData">входные данные</param>
        /// <param name="sInType">входной тип</param>
        /// <param name="sOutType">выходной тип</param>
        /// <returns>Данные выходного типа</returns>
        /// <remarks>The fuction has bad code style</remarks>
        public override String ConvertDataTo(string sInData, ItemType sInType, ItemType sOutType)
        {
            if(sInType == ItemType.Clicks) return null;//cant be!
            if(sOutType == ItemType.User) return null;//cant be!
            if (sInType == sOutType) return sInData;

            //
            string url = null;
            if(sInType == ItemType.FullUrl)
            {
                url = String.Format("http://cli.gs/api/{0}/cligs/create?url={1}{2}", _version, HttpUtility.UrlEncode(sInData),
                                    (String.IsNullOrEmpty(_apikey) ? "" : "&key=" + _apikey));
            }
            if (sOutType == ItemType.FullUrl)
            {
                url = String.Format("http://cli.gs/api/{0}/cligs/expand?clig={1}{2}", _version, HttpUtility.UrlEncode(sInData),
                                    (String.IsNullOrEmpty(_apikey) ? "" : "&key=" + _apikey));
            }

            if (url == null) return null;
            try
            {
                HttpWebRequest request = MakeRequest(url); //prepare web request
                HttpWebResponse resp = (HttpWebResponse) request.GetResponse();
                StreamReader responseStream = new StreamReader(resp.GetResponseStream()); //prepare responese holder
                String response = responseStream.ReadToEnd(); //fill up response
                responseStream.Close(); //Close stream
                if (resp.StatusCode == HttpStatusCode.OK)
                {
                    return response;
                }
            }catch(Exception e1)
            {
                Debug.WriteLine(e1);
            }
            return null;
        }
    }
}
